<template>
  <div>
    <div class="uploadFile uploadFile_1">
      <span style="float:left; padding-top:5.5px;">上传数据：</span>
      <a-upload
        accept=".xls, .xlsx"
        :data="param"
        :action="uploadUrl"
        :headers="headers"
        :beforeUpload="beforeUpload"
        :file-list="fileList"
        @change="handleChange"
        style="display:inline-block;  min-width: 154px;"
      >
        <a-button class="mr20" v-if="fileList.length < length">
          <a-icon type="upload" />上传Excel文件
        </a-button>
      </a-upload>
      <a-button class="mr20" ghost type="primary" @click="download">下载模板</a-button>
      <a-button type="primary" @click="confirmImport">确定预装船</a-button>
    </div>
    <div class="dataSource">
      <a-list v-if="data.length===0" />
      <a-table
        v-else
        :columns="columns"
        :loading="loading"
        :data-source="data"
        style="margin-top:25px;"
        :scroll="{x:1600,y:450}"
        :pagination="false"
        :row-class-name="record => record.canImport===1 ? '' : 'redRow'"
        :row-key="(record,index) => index"
      >
        <template slot="status" slot-scope="record">
          <span v-if="record.containerStatus === 'A'">A</span>
          <span v-else-if="record.containerStatus === 'COMMON'">普通</span>
          <span v-else-if="record.containerStatus === 'BROKEN'">坏箱</span>
          <span v-else-if="record.containerStatus === 'DIRTY'">污箱</span>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import { commonExport } from '@/api/request'
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import md5 from 'md5'
import store from 'store'
import Util from '@/common/util'
import reqwest from 'reqwest'
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '箱号',
    dataIndex: 'containerNo'
  },
  {
    title: '封号',
    customRender: (text, record, index) => {
      return record.containerSealNo ? record.containerSealNo : '--'
    }
  },
  {
    title: '运单号',
    width: 150,
    customRender: (text, record, index) => {
      return record.seagoingShipOrderCode
        ? record.seagoingShipOrderCode
        : '--'
    }
  },
  {
    title: '持箱人',
    dataIndex: 'holder',
    width: 200
  },
  {
    title: '箱属',
    dataIndex: 'containerBelong'
  },
  {
    title: '始发港',
    customRender: (text, record, index) => {
      return record.startPortName ? record.startPortName : '--'
    }
  },
  {
    title: '目的港',
    customRender: (text, record, index) => {
      return record.endPortName ? record.endPortName : '--'
    }
  },
  {
    title: '箱型',
    dataIndex: 'containerType'
  },
  {
    title: '箱态',
    customRender: (text, record, index) => {
      return record.emptyOrHeavy === 1 ? '空' : '重'
    }
  },
  {
    title: '箱况',
    scopedSlots: {
      customRender: 'status'
    }
  },
  {
    title: '货名',
    customRender: (text, record, index) => {
      return record.goodsName ? record.goodsName : '--'
    }
  },
  {
    title: '货重（吨）',
    customRender: (text, record, index) => {
      return record.goodsWeight ? record.goodsWeight : '--'
    }
  }
]
export default {
  name: 'uploadFile',
  data () {
    return {
      param: {},
      fileList: [],
      previewVisible: false,
      previewImage: '',
      loading: false,
      headers: {},
      file: {},
      uploadUrl:
        REQUEST_INTEFACE_URL + '/order/previewAdvanceLoadContainerFromExcel',
      columns,
      data: [],
      useableNumber: 0
    }
  },
  props: {
    length: {
      type: Number,
      default: 100
    },
    fileObj: Object
  },
  computed: {},
  methods: {
    downloadRequest () {
      commonExport('/common/downloadExcelTemplate', {
        name: '预装船导入模板.xls'
      })
    },
    beforeUpload () {
      const uuid = Util.getUUID()
      const headers = {
        appKey: APP_KEY,
        version: VERSION_NO,
        timestamp: (() => new Date().getTime())(),
        nonce: uuid,
        token: store.get('token') ? store.get('token') : '',
        sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
      }
      this.headers = headers
      // // console.log(headers)
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList
      this.file = file
      // // console.log(fileList)
      // // console.log(file)
      if (file.status === 'done') {
        this.data = file.response.data
        this.data.forEach(v => {
          if (v.canImport === 1) {
            this.useableNumber++
          }
        })
      } else if (file.status === 'removed') {
        this.data = []
        this.useableNumber = 0
      }
    },
    confirmImport () {
      if (this.data.length === 0 || this.useableNumber === 0) {
        this.$message.warning('没有可导入的完整的集装箱！')
        return false
      }
      let _self = this
      const h = _self.$createElement

      _self.$confirm({
        title: h('div', {}, [
          h('span', '确定导入此'),
          h(
            'span',
            { style: { padding: '0 3px', color: 'orange', fontSize: '20px', lineHeight: '22px' } },
            _self.useableNumber
          ),
          h('span', '个数据完整的集装箱？')
        ]),
        onOk () {
          const formData = new FormData()
          const fileUrl =
            REQUEST_INTEFACE_URL + '/order/advanceLoadContainerFromExcel'
          formData.append('file', _self.file.originFileObj)
          formData.append('voyageId', _self.param.voyageId)
          formData.append('portId', _self.param.portId)
          const uuid = Util.getUUID()
          reqwest({
            url: fileUrl,
            method: 'post',
            headers: {
              appKey: APP_KEY,
              version: VERSION_NO,
              timestamp: (() => new Date().getTime())(),
              nonce: uuid,
              token: store.get('token') ? store.get('token') : '',
              sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
            },
            processData: false,
            data: formData,
            success: res => {
              // console.log(res)
              if (res.code === 0) {
                _self.$message.success('文件上传成功！')
                _self.$emit('uploadFile', true)
              } else {
                _self.$message.error(res.message)
              }
            },
            error: () => {
              _self.$message.error('文件上传失败！')
            }
          })
        }
      })
    },
    download () {
      this.downloadRequest()
    }
  },
  mounted () {
    this.param = this.fileObj
    // // console.log(this.fileObj)
  }
}
</script>
<style>
/* .ant-upload-list {
  width: 200px;
  display: inline-block !important;
} */
.mr20 {
  margin-right: 20px;
}
.dataSource {
  padding: 20px 0;
}
.redRow {
  background: tomato;
}
</style>
